package com.czl.module_storehouse.activity.intostore;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.PopupWindow;
import android.widget.TextView;

import androidx.core.content.ContextCompat;
import androidx.core.widget.PopupWindowCompat;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.czl.base.config.AppConstants;
import com.czl.base.data.bean.tengyun.SortBean;
import com.czl.base.util.SpHelper;
import com.czl.module_base.bean.CompanyBean;
import com.czl.module_base.bean.ListBean;
import com.czl.module_base.http.HttpResponse;
import com.czl.module_base.mvp.presenter.InjectPresenter;
import com.czl.module_base.mvp.view.SimpleView;
import com.czl.module_base.utils.NumberUtils;
import com.czl.module_service.system.Constants;
import com.czl.module_storehouse.R;
import com.czl.module_storehouse.activity.base.BaseOperationActivity;
import com.czl.module_storehouse.activity.intostore.record.WarehouseRecordActivity;
import com.czl.module_storehouse.activity.intostore.saveloc.SaveLocActivity;
import com.czl.module_storehouse.activity.intostore.selectgoods.SelectGoodsActivity;
import com.czl.module_storehouse.activity.intostore.selectorder.SelectOrderActivity;
import com.czl.module_storehouse.activity.managegoods.add.GoodsAddActivity;
import com.czl.module_storehouse.adapter.AddWareHouseAdapter;
import com.czl.module_storehouse.bean.AddStorageBean;
import com.czl.module_storehouse.bean.PurchaseBean;
import com.czl.module_storehouse.bean.PurchaseProjectListBean;
import com.czl.module_storehouse.bean.StorageTypeModel;
import com.czl.module_storehouse.databinding.ActivityBaseOperationBinding;
import com.czl.module_storehouse.databinding.HeaderAddWareHouseBinding;
import com.czl.module_storehouse.databinding.MenuAddWareHouseBinding;
import com.czl.module_storehouse.event.AddWareHouseEvent;
import com.czl.module_storehouse.event.AddWareSortEvent;
import com.czl.module_storehouse.event.PurchaseEvent;
import com.czl.module_storehouse.event.SaveLocationEvent;
import com.czl.module_storehouse.event.SortEvent;
import com.czl.module_storehouse.mvp.presenter.AddWareHousePresenter;
import com.czl.module_storehouse.mvp.presenter.CompanyPresenter;
import com.czl.module_base.widget.timeselector.TimeSelector;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author xubin
 */
@Route(path = AppConstants.Router.Service.F_SERVICE_WAREHOUSING_HOME)
public class AddWareHouseActivity extends BaseOperationActivity<ActivityBaseOperationBinding> implements SimpleView {

    private static final int TYPE_ADD_OTHER = 0;
    private static final int TYPE_ADD_PURCHASE = 1;

    private AddWareHouseAdapter mAdapter;
    private List<StorageTypeModel> mStorageTypeModels;
    private AddStorageBean mAddStorageBean = new AddStorageBean();

    private SortBean mSortBean;
    private List<CompanyBean> mCompanyBeanList;
    private int mStorageTypeModelVal;
    private HeaderAddWareHouseBinding mHeaderBinding;
    @InjectPresenter
    AddWareHousePresenter mAddWareHousePresenter;
    @InjectPresenter
    CompanyPresenter mCompanyPresenter;

    @Override
    protected ActivityBaseOperationBinding getBinding(LayoutInflater layoutInflater) {
        return ActivityBaseOperationBinding.inflate(layoutInflater);
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);
        mToolBinding.toolbarContentTitle.setText("物品入库");
        mToolBinding.toolbarRightImg.setVisibility(View.VISIBLE);
        mToolBinding.toolbarRightImg.setBackgroundResource(R.drawable.ic_more_horiz_black_24dp);
        binding.btnSure.setText("入库");
        binding.recyclerView.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false));
        binding.recyclerView.setAdapter(getAdapter());
        mToolBinding.toolbarRightImg.setOnClickListener(v -> showMenu());
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }

    @Override
    protected BaseQuickAdapter<SortBean, ?> getAdapter() {
        if (mAdapter == null) {
            mAdapter = new AddWareHouseAdapter(R.layout.item_add_ware_house);
            mAdapter.setOnItemChildClickListener((adapter, view, position) -> {
                SortBean item = mAdapter.getItem(position);
                onItemClickData(view, item, position);
            });
            mAdapter.setOnNumChangeListener(count -> setButtonState(getTotalCountNum()));
            mHeaderBinding = HeaderAddWareHouseBinding.inflate(getLayoutInflater());
            mHeaderBinding.llCommonAdd.tvAddGoods.setText("选择物品");
            mHeaderBinding.tvTypeHead.setOnClickListener(v -> showPopupWindowStorageType());
            mHeaderBinding.tvSupplier.setOnClickListener(v -> showPopupCrmCompany());
            mHeaderBinding.stvSelectedSupplier.setOnClickListener(v -> selectOrder());
            mHeaderBinding.llCommonAdd.llAdd.setOnClickListener(v -> goGoodsActivity());
            mAdapter.addHeaderView(mHeaderBinding.getRoot());
            addFooterView(mAdapter);
        }
        return mAdapter;
    }

    @Override
    protected Button getButton() {
        return binding.btnSure;
    }

    private void onItemClickData(View itemView, SortBean sortBean, int position) {
        mSelectedPosition = position;
        mSortBean = sortBean;
        int id = itemView.getId();
        if (id == R.id.tv_product_loc || id == R.id.iv_right) {
            goLocActivity(sortBean);
        } else if (id == R.id.tv_date) {
            if (itemView instanceof TextView) {
                TextView textView = (TextView) itemView;
                showTimeSelector(textView, time -> {
                    sortBean.setManufactureDate(time);
                    mAdapter.setData(mSelectedPosition, sortBean);
                });
            }
        } else if (id == R.id.tv_add_goods) {
            goAddGoodsActivity(sortBean);
        }
    }

    private void showTimeSelector(TextView textView, TimeSelector.ResultHandler resultHandler) {
        TimeSelector timeSelector = new TimeSelector(this, time ->
        {
            textView.setText(time);
            resultHandler.handle(time);
        }, "1990-01-01", "2099-12-31", TimeSelector.FORMAT_STR2, new Date());
        timeSelector.setScrollUnit(TimeSelector.SCROLLTYPE.YEAR,
                TimeSelector.SCROLLTYPE.MONTH,
                TimeSelector.SCROLLTYPE.DAY);
        timeSelector.show();
    }

    private void goAddGoodsActivity(SortBean item) {
        AddWareSortEvent sortEvent = new AddWareSortEvent(item.getAssetType());
        sortEvent.setSortBean(item);
        EventBus.getDefault().postSticky(sortEvent);
        getContext().startActivity(new Intent(getContext(), GoodsAddActivity.class));
    }

    private void showMenu() {
        MenuAddWareHouseBinding binding = MenuAddWareHouseBinding.inflate(getLayoutInflater());
        PopupWindow window = new PopupWindow(getContext());
        window.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);
        window.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        window.setContentView(binding.getRoot());
        window.setFocusable(true);
        window.setTouchable(true);
        window.setOutsideTouchable(true);
        window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        PopupWindowCompat.showAsDropDown(window, mToolBinding.toolbarRightImg, 20, 0, Gravity.END);
        binding.tvMenuTitle.setOnClickListener(v -> goRecordActivity());
    }

    private void goRecordActivity() {
        startActivity(new Intent(getContext(), WarehouseRecordActivity.class));
    }

    @Subscribe(threadMode = ThreadMode.POSTING, sticky = true)
    public void onDataEvent(SortEvent event) {
        SortBean sortBean = event.getSortBean();
        if (sortBean == null) {
            return;
        }
        if (mStorageTypeModelVal != TYPE_ADD_OTHER) {
            List<SortBean> data = mAdapter.getData();
            if (data.isEmpty()) {
                return;
            }
            for (int i = 0; i < data.size(); i++) {
                SortBean bean = data.get(i);
                String sortName = bean.getSortName();
                String sortModel = bean.getSortModel();

                if (TextUtils.isEmpty(sortName)) {
                    continue;
                }
                if (TextUtils.isEmpty(sortModel)) {
                    continue;
                }
                Integer propCompanyId = bean.getPropCompanyId();
                if (propCompanyId == null || 0 == propCompanyId) {
                    continue;
                }
                if (sortName == null) {
                    continue;
                }
                if (sortModel == null) {
                    continue;
                }
                if (sortName.equals(sortBean.getSortName())
                        && sortModel.equals(sortBean.getSortModel())
                        && propCompanyId.equals(sortBean.getPropCompanyId())) {
                    bean.setSortId(sortBean.getSortId());
                    mAdapter.setData(i, bean);
                }
            }
            return;
        }
        mSortBean.setSortId(sortBean.getSortId());
        mAdapter.setData(mSelectedPosition, mSortBean);
    }

    /**
     * 选择采购单
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.POSTING, sticky = true)
    public void onDataEvent(PurchaseEvent event) {
        if (event == null) {
            return;
        }
        if (event.getPurchaseBean() == null) {
            return;
        }
        mHeaderBinding.tvSupplier.setText(event.getPurchaseBean().getSupplyCompanyNameStr());
        mHeaderBinding.stvSelectedSupplier.setRightString(event.getPurchaseBean().getCardName());
        mAddStorageBean.setContractNo(event.getPurchaseBean().getCardNo());
        mAddStorageBean.setContractId(event.getPurchaseBean().getPurchaseCardId());
        mAddStorageBean.setContractName(event.getPurchaseBean().getCardName());
        mateSortList(getListByPurchase(event.getPurchaseBean()));
    }

    public List<SortBean> getListByPurchase(PurchaseBean bean) {
        if (bean == null) {
            return new ArrayList<>();
        }
        List<PurchaseProjectListBean> cardProjectList = bean.getCardProjectList();
        if (cardProjectList == null || cardProjectList.isEmpty()) {
            return new ArrayList<>();
        }
        List<SortBean> list = new ArrayList<>();
        for (PurchaseProjectListBean listBean : cardProjectList) {
            SortBean sortBean = new SortBean();
            sortBean.setSortModel(listBean.getModel());
            sortBean.setSortName(listBean.getPurchaseName());
            sortBean.setPropCompanyId(Integer.valueOf(bean.getParentCompanyId()));
            sortBean.setPrice(listBean.getPrice());
            sortBean.setStorageNum(listBean.getUnInstoreCount());
            sortBean.setOrganizationId(listBean.getOrganizationId());
            sortBean.setAssetType(listBean.getAssetType());
            list.add(sortBean);
        }
        return list;
    }

    private void mateSortList(List<SortBean> list) {
        if (mAddWareHousePresenter != null) {
            mAddWareHousePresenter.mateSortList(list);
        }
    }

    @Override
    protected void loadData() {
        super.loadData();
        //查询入库类型
        getStorageModel();
        selectCrmCompanyByTag();
    }

    private void getStorageModel() {
        if (mAddWareHousePresenter != null) {
            mAddWareHousePresenter.getStorageModel();
        }
    }

    private void selectCrmCompanyByTag() {
        if (mCompanyPresenter != null) {
            mCompanyPresenter.selectCrmCompanyByTag();
        }
    }

    @Override
    public <T> void showHttpResponse(HttpResponse<T> httpResponse) {
        super.showHttpResponse(httpResponse);
        if (AddWareHousePresenter.TAG_STORAGE_MODEL.equals(httpResponse.getRequestTag())) {
            mStorageTypeModels = (List<StorageTypeModel>) httpResponse.getData();
        } else if (AddWareHousePresenter.TAG_STORAGE_ADD.equals(httpResponse.getRequestTag())) {
            showToast("入库成功");
            resetData();
        } else if (CompanyPresenter.TAG_COMPANY_LIST.equals(httpResponse.getRequestTag())) {
            mCompanyBeanList = ((ListBean<CompanyBean>) httpResponse.getData()).getList();
        } else if (AddWareHousePresenter.TAG_STORAGE_MATE_SORT_LIST.equals(httpResponse.getRequestTag())) {
            if (httpResponse.getData() instanceof ListBean) {
                ListBean<SortBean> data = (ListBean<SortBean>) httpResponse.getData();
                if (data != null && data.getList() != null) {
                    mAdapter.setOrder(true);
                    mAdapter.setList(data.getList());
                    List<SortBean> list = data.getList();
                    StringBuilder sb = new StringBuilder();
                    for (SortBean bean : list) {
                        String organizationId = bean.getOrganizationId();
                        sb.append(organizationId).append(",");
                    }
                    mAddStorageBean.setStorageOrgId(sb.toString());
                }
            }
        }
    }

    private void resetData() {
        mStorageTypeModelVal = 0;
        mAddStorageBean.setStorageModel(null);
        mAddStorageBean = new AddStorageBean();
        mHeaderBinding.tvTypeHead.setText("选择入库类型");
        mHeaderBinding.tvSupplier.setText("选择供应商");
        mHeaderBinding.etDeliveryMan.setText("");
        mHeaderBinding.stvSelectedSupplier.setVisibility(View.GONE);
        mHeaderBinding.tvSupplier.setEnabled(true);
        mFooterBinding.etRemark.setText("");
        mAdapter.setList(new ArrayList<>());
    }

    /**
     * 选择位置
     *
     * @param sortBean
     */
    private void goLocActivity(SortBean sortBean) {
        if (sortBean == null) {
            showToast("物品信息不存在");
            return;
        }
        Integer sortId = sortBean.getSortId();
        if (sortId == null || sortId == 0) {
            showToast("该物品不存在，请创建物品");
            return;
        }
        if (mStorageTypeModelVal == TYPE_ADD_PURCHASE) {
            //采购
            EventBus.getDefault().postSticky(new SaveLocationEvent(sortBean, sortBean.getStorageNum() == null
                    ? 0 : sortBean.getStorageNum(), false));
        } else {
            EventBus.getDefault().postSticky(new SaveLocationEvent(sortBean, Integer.MAX_VALUE, false));
        }
        startActivity(new Intent(getContext(), SaveLocActivity.class));
    }

    @Override
    protected void submit() {
        //添加入库
        if (mAddStorageBean.getStorageModel() == null) {
            showToast("请选择入库类型");
            return;
        }

        /*String text = mHeaderBinding.tvSupplier.getText().toString();
        if ("选择供应商".equals(text)) {
            mAddStorageBean.setSupplier(null);
        } else {
            mAddStorageBean.setSupplier(text);
        }
        String companyName = mHeader.mSelectedBean.getCompanyName();
        if (text.equals(companyName)) {
            mAddStorageBean.setSupplierId(mHeader.mSelectedBean.getCompanyId());
        } else {
            mAddStorageBean.setSupplierId(null);
        }*/
        String supplier = mHeaderBinding.tvSupplier.getText().toString();
        mAddStorageBean.setSupplier(supplier);
//        mAddStorageBean.setSupplier(mHeader.autoCompleteTextView.getText().toString());
//        if (TextUtils.isEmpty(mAddStorageBean.getSupplier())) {
//            showToast("请选择供应商");
//            return;
//        }
        String delivery = mHeaderBinding.etDeliveryMan.getText().toString();
        mAddStorageBean.setTransmitter(delivery);
        mAddStorageBean.setSortList(mAdapter.getData());
        String remark = mFooterBinding.etRemark.getText().toString();
        mAddStorageBean.setStorageConment(remark);
        if (mAdapter.getData().isEmpty()) {
            showToast("入库物品不能为空");
            return;
        }
        SortBean notExistedSort = isNotExistedSort(mAdapter.getData());
        if (notExistedSort != null) {
            showToast(notExistedSort.getSortName() + "不存在，请创建物品");
            return;
        }
        int storageModel = mAddStorageBean.getStorageModel();
        if (TYPE_ADD_PURCHASE == storageModel) {
            if (!isAllStorageNum(mAdapter.getData())) {
                showToast("入库数量与采购数量不一致");
                return;
            }
        }
        for (SortBean sortBean : mAdapter.getData()) {
            if (TextUtils.isEmpty(sortBean.getPrice())) {
                showToast(sortBean.getSortName() + "价格不能为空，请输入物品价格");
                return;
            }
            if (NumberUtils.isDouble(sortBean.getPrice())) {
                double price = Double.parseDouble(sortBean.getPrice());
                if (price < 0.000001) {
                    showToast(sortBean.getSortName() + "价格不能为空，请输入物品价格");
                    return;
                }
            }
        }
        if (mAddWareHousePresenter != null) {
            mAddWareHousePresenter.addStorage(mAddStorageBean);
        }
    }

    public SortBean isNotExistedSort(List<SortBean> list) {
        if (list == null || list.isEmpty()) {
            return null;
        }
        for (SortBean sortBean : list) {
            if (sortBean.getSortId() == null || sortBean.getSortId() == 0) {
                return sortBean;
            }
        }
        return null;
    }

    public boolean isAllStorageNum(List<SortBean> list) {
        if (list == null || list.isEmpty()) {
            return false;
        }
        for (SortBean sortBean : list) {
            if (sortBean.getStorageNum() == null) {
                continue;
            }
            if (sortBean.getStorageNum() > sortBean.getTotalStorageNum(SpHelper.INSTANCE.decodeInt(Constants.SpKey.STOREHOUSE_LOCATION_ID))) {
                return false;
            }
        }
        return true;
    }

    /**
     * 选择供应商
     */
    private void showPopupCrmCompany() {
        if (mCompanyBeanList == null || mCompanyBeanList.isEmpty()) {
            showToast("没有供应商");
            return;
        }
        List<String> strings = new ArrayList<>();
        for (CompanyBean bean : mCompanyBeanList) {
            String name = bean.getCompanyName();
            if (!TextUtils.isEmpty(name)) {
                strings.add(name);
            }
        }
        showRecyclerViewPopupWindow(strings, "选择供应商", (adapter, view, position) -> {
            CompanyBean bean = mCompanyBeanList.get(position);
            mAddStorageBean.setSupplierId(bean.getCompanyId());
            mAddStorageBean.setSupplier(bean.getCompanyName());
            mHeaderBinding.tvSupplier.setText(bean.getCompanyName());
        });
    }

    private void goGoodsActivity() {
        AddWareHouseEvent event = new AddWareHouseEvent(mAdapter.getData());
        EventBus.getDefault().postSticky(event);
        startActivity(new Intent(getContext(), SelectGoodsActivity.class));
    }

    /**
     * 选择采购单
     */
    private void selectOrder() {
        startActivity(new Intent(getContext(), SelectOrderActivity.class));
    }

    /**
     * 选择入库类型
     */
    private void showPopupWindowStorageType() {
        if (mStorageTypeModels == null || mStorageTypeModels.size() == 0) {
            return;
        }
        List<String> strings = new ArrayList<>();
        for (StorageTypeModel model : mStorageTypeModels) {
            strings.add(model.getDesc());
        }
        showRecyclerViewPopupWindow(strings, "选择入库类型", (adapter, view, position) -> {
            StorageTypeModel storageTypeModel = mStorageTypeModels.get(position);
            mHeaderBinding.tvTypeHead.setText(storageTypeModel.getDesc());
            mStorageTypeModelVal = storageTypeModel.getVal();
            mAddStorageBean.setStorageModel(mStorageTypeModelVal);
            resetListData();
            if (TYPE_ADD_OTHER == mStorageTypeModelVal) {
                //其它入库
                mHeaderBinding.stvSelectedSupplier.setVisibility(View.GONE);
                mHeaderBinding.llCommonAdd.llCommonAdd.setVisibility(View.VISIBLE);
                mHeaderBinding.tvSupplier.setEnabled(true);
                mHeaderBinding.tvSupplier.setVisibility(View.VISIBLE);
                setDrawable(mHeaderBinding.tvSupplier);
                if (mAddStorageBean != null) {
                    mAddStorageBean.setContractNo(null);
                }
                mAdapter.setOrder(false);
            } else if (TYPE_ADD_PURCHASE == mStorageTypeModelVal) {
                //采购入库
                mHeaderBinding.stvSelectedSupplier.setVisibility(View.VISIBLE);
                mHeaderBinding.llCommonAdd.llCommonAdd.setVisibility(View.GONE);
                mHeaderBinding.tvSupplier.setText("");
                mHeaderBinding.tvSupplier.setEnabled(false);
                mHeaderBinding.tvSupplier.setCompoundDrawables(null, null, null, null);
            }
        });
    }

    private void setDrawable(TextView view) {
        Drawable drawable = ContextCompat.getDrawable(getContext(), R.drawable.ic_right);
        if (drawable != null) {
            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
            view.setCompoundDrawables(null, null, drawable, null);
        }
    }

    private void resetListData() {
        mHeaderBinding.tvSupplier.setText("选择供应商");
        mAdapter.setList(new ArrayList<>());
    }

}
